package com.woniuxy.lab.woniu_lab.util;

import com.alibaba.fastjson.JSON;
import com.woniuxy.lab.woniu_lab.commons.MsgParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * 短信工具类，调用蜗牛学苑短信接口发送短信
 */
@Slf4j
public class SmsUtils {

    /**
     * 发送任意短信内容，但请先申请模板
     *
     * @param captcha  验证码
     * @param mobileNumber  手机号
     */
    public static void sendSms(String captcha, String mobileNumber) throws URISyntaxException {
        log.info("content:{}", captcha);
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        URI uri = new
                URIBuilder().setScheme("http").setHost("old.woniuxy.com").setPort(8081)
                .setPath("/msg/sendMsg").build();

        MsgParam param = new MsgParam();
        param.setCode(captcha);//支持[0-9][a-z][A-Z]
        param.setPhoneNum(mobileNumber);//发送手机号码

        // 创建Post请求
        HttpPost httpPost = new HttpPost(uri);
        StringEntity entity = new StringEntity(JSON.toJSONString(param), "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        entity.setContentType(ContentType.APPLICATION_JSON.toString());
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            log.debug("响应状态为 :{}", response.getStatusLine());
            if
            (responseEntity != null) {
                log.debug("响应内容长度为 :{}",
                        responseEntity.getContentLength());
                log.debug("响应内容为 :{}",
                        EntityUtils.toString(responseEntity));
            }
        } catch ( ParseException | IOException e) {
            log.error("短信发送出错",e);
            throw new RuntimeException(e);
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭短信发送链接请求出错",e);
            }
        }
    }
}